package com.seele.tigerwallet.ui.fragment;


import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.zxing.activity.CaptureActivity;
import com.seele.tigerwallet.R;
import com.seele.tigerwallet.api.APIException;
import com.seele.tigerwallet.api.APIListCallBack;
import com.seele.tigerwallet.api.APIModule;
import com.seele.tigerwallet.async.Log;
import com.seele.tigerwallet.model.AssetsModel;
import com.seele.tigerwallet.model.UserInfo;
import com.seele.tigerwallet.ui.activtiy.AddAssetsActivity;
import com.seele.tigerwallet.ui.activtiy.ScanActivity;
import com.seele.tigerwallet.ui.activtiy.TokenIntercourseActivity;
import com.seele.tigerwallet.ui.adapter.AssetsAdapter;
import com.seele.tigerwallet.ui.base.BaseFragment;
import com.seele.tigerwallet.ui.callback.AppBarStateChangeListener;
import com.seele.tigerwallet.ui.event.AssetsEvent;
import com.seele.tigerwallet.ui.event.ExchangeEvent;
import com.seele.tigerwallet.ui.event.MessageEvent;
import com.seele.tigerwallet.ui.manager.DaoManager;
import com.seele.tigerwallet.ui.utils.ArithUtil;
import com.seele.tigerwallet.ui.utils.DataUtils;
import com.seele.tigerwallet.ui.utils.SPUtils;
import com.seele.tigerwallet.ui.utils.SqlUtil;
import com.seele.tigerwallet.ui.utils.TypefaceUtils;
import com.seele.tigerwallet.utils.Constants;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

/**
 * @Author: 郑波
 * @Time: 2018/6/7 19:56
 * @Description: 资产界面
 */
public class AssetsFragment extends BaseFragment {
    private static AssetsFragment assetsFragment;
    private RecyclerView mRecyclerView;
    private FloatingActionButton mFloatingActionButton;
    private CollapsingToolbarLayout mCollapsingToolbarLayout;
    private AppBarLayout mAppBarLayout;
    private Toolbar mToolbar;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private AssetsAdapter mAssetsAdapter;
    private String mAddress;
    private List<AssetsModel> mAssetsModelList;
    private String mTotal = "0.00";//总值
    private TextView mTotalTextView;
    private List<AssetsModel> mResponse;
    private boolean isResume;
    private int mDif;
    private ImageView mImageView;
    boolean isShow;


    private int mState;

    public static AssetsFragment newInstanec() {
        if (assetsFragment == null) {
            assetsFragment = new AssetsFragment();
        }
        return assetsFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_assets;

    }

    @Override
    protected void initView() {
        mToolbar = $f(R.id.toolbar);
        ((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar);
        setAdapter();
        mDif = (int) getResources().getDimension(R.dimen.dP_50);

        initViews();
        //获取本地数据
        initLoadlocal();

    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_main, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_scanning) {//跳转扫描界面
            Bundle bundle = new Bundle();
            bundle.putInt(CaptureActivity.class.getSimpleName(), CaptureActivity.ASSETSF);
            startActivity(ScanActivity.class, bundle);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    //初始化控件
    private void initViews() {
        mImageView = $f(R.id.switch_img);
        mFloatingActionButton = $f(R.id.floatingActionButton);
        mSwipeRefreshLayout = $f(R.id.swipeRefreshLayout);
        mFloatingActionButton.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#63D0AB")));
        mCollapsingToolbarLayout = $f(R.id.collapsing_toolbar);
        mCollapsingToolbarLayout.setExpandedTitleGravity(Gravity.CENTER);
        mCollapsingToolbarLayout.setExpandedTitleMargin(0, 0, 0, (int) getResources().getDimension(R.dimen.dp_30));
        mAppBarLayout = $f(R.id.appbar);
        mTotalTextView = $f(R.id.total_tv);

        mSwipeRefreshLayout.setColorSchemeResources(R.color.color_63D0AB, R.color.color_FC6262);


//        mSwipeRefreshLayout.setProgressViewEndTarget(true,200);
        mSwipeRefreshLayout.setProgressViewOffset(true, -20, (int) getResources().getDimension(R.dimen.dp_50));
        mAppBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener(mDif) {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state, int i) {
                if (state == State.EXPANDED) {
                    mState = 1;
                    mSwipeRefreshLayout.post(new Runnable() {
                        @Override
                        public void run() {
                            mSwipeRefreshLayout.setEnabled(true);
                        }
                    });
                    setAssetsATitleByAtate();
                } else if (state == state.IDLE) {
                    mState = 2;
                    setAssetsATitleByAtate();
                    mSwipeRefreshLayout.post(new Runnable() {
                        @Override
                        public void run() {
                            mSwipeRefreshLayout.setEnabled(false);
                        }
                    });

                }

            }
        });

        isShow = DataUtils.isShow();
        setAssetsATitle(DataUtils.getCompany());
        mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转至添加资产界面
                if (null != mAssetsModelList && mAssetsModelList.size() > 0) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(AddAssetsActivity.class.getSimpleName(), (Serializable) mAssetsModelList);
                    startActivity(AddAssetsActivity.class, bundle);
                } else {
                    startActivity(AddAssetsActivity.class);
                }
            }
        });

        mAssetsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //跳转至转账界面
                Bundle bundle = new Bundle();
                AssetsModel model = mAssetsModelList.get(position);
                bundle.putSerializable(TokenIntercourseActivity.class.getSimpleName(), model);
                startActivity(TokenIntercourseActivity.class, bundle);

            }
        });

        //资产隐藏显示控件
        mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isShow) {
                    isShow = false;
                } else {
                    isShow = true;
                }
                SPUtils.putBoolean(SPUtils.ASSET_SHOW, isShow);
                setTotalAndTitle();
            }
        });


        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (mState == 1) {
                    Log.e("setOnRefreshListener", "::::1111111111:");
                    handlerData(false);
                }

//                mSwipeRefreshLayout.setEnabled(true);

            }
        });
    }

    /**
     * 根据状态修改标题
     */
    private void setAssetsATitleByAtate() {
        setTotalAndTitle();
        if (mState == 1) {
            setAssetsATitle(DataUtils.getCompany());
            mTotalTextView.setVisibility(View.VISIBLE);
//            TypefaceUtils.setFuturaMediumBT(mTotalTextView,mContext);
            mImageView.setVisibility(View.VISIBLE);
        } else if (mState == 2) {
            if (isShow) {
                setAssetsATitle(DataUtils.getCompany() + ": " + "*****");
            } else {
                setAssetsATitle(DataUtils.getCompany() + ": " + mTotal);
            }
            mTotalTextView.setVisibility(View.GONE);
            mImageView.setVisibility(View.GONE);
        } else {
            setAssetsATitle(DataUtils.getCompany());
//            mTotalTextView.setVisibility(View.VISIBLE);
//            mImageView.setVisibility(View.VISIBLE);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {//TODO 需要子线程处理
        if (event instanceof AssetsEvent) {
            try {
                AssetsEvent assetsEvent = (AssetsEvent) event;
                List<AssetsModel> assetsModelList = assetsEvent.mAssetsModelList;
                if (null != assetsModelList && assetsModelList.size() > 0) {
                    List<Integer> list = new ArrayList<>();
                    for (AssetsModel assetsModel : assetsModelList) {
                        list.add(assetsModel.id);
                    }
                    for (AssetsModel assetsModel : mAssetsModelList) {
                        if (!list.contains(assetsModel.id)) {
                            DaoManager.getAssetsDao().delete(assetsModel);
                        }
                    }
                    mAssetsModelList = assetsEvent.mAssetsModelList;
                }
                setNewData();
                handlerData(false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (event instanceof ExchangeEvent) {//转账界面返回刷新数据

            onHiddenChanged();

        }


    }


    //获取本地数据
    private void initLoadlocal() {
        mAddress = UserInfo.get().address;
        if (TextUtils.isEmpty(mAddress)) {
            return;
        }
        try {
            //查询被动数据
            mAssetsModelList = SqlUtil.getAssetsModel(SqlUtil.queryAssetsFromAsc());
            if (null != mAssetsModelList && mAssetsModelList.size() > 0) {
                calculatedValue();
                setNewData();
                handlerData(true);
            } else {
                initFirstData();
//                mAssetsAdapter.setEmptyView(EmpteyView.getDataFailedView(mContext));
            }
            setTotalAndTitle();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 第一次请求数据
     */
    private void initFirstData() {

//        mSwipeRefreshLayout.post(new Runnable() {
//            @Override
//            public void run() {
//                mSwipeRefreshLayout.setEnabled(false);
//                mSwipeRefreshLayout.setRefreshing(true);
//
//            }
//        });
//        Log.e("initFirstData", "::::获取第一次数据:");


        APIModule
                .getApi()
                .balanceFixedlist()
                .enqueue(new APIListCallBack<AssetsModel>() {
                    @Override
                    protected void onResponseError(APIException e) {
//                        onFirstLoad();
                    }

                    @Override
                    protected void onFailureError(Call<String> call, Throwable t) {
//                        onFirstLoad();
                    }

                    @Override
                    protected void onResponse(List<AssetsModel> response) {
//                        onFirstLoad();
                        try {
                            if (null != response && response.size() > 0) {
                                mAssetsModelList = response;
                                sortList();
                                calculatedValue();
                                handlerData(true);
                            }

                            setTotalAndTitle();
                            setNewData();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }
                });


    }

    private void onFirstLoad() {
        mSwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setEnabled(true);
                mSwipeRefreshLayout.setRefreshing(false);

            }
        });
    }

    private void calculatedValue() {
        mTotal = "0.00";

        for (AssetsModel assetsModel : mAssetsModelList) {
            //计算每个token的总价并
            String total = DataUtils.getAssetsTotal(assetsModel.price, assetsModel.balance);
            mTotal = ArithUtil.add(mTotal, total);
        }

    }


    //设置总价格
    private void setTotalAndTitle() {

        setAssetsATitle(DataUtils.getCompany());
        //设置总资产
        if (isShow) {
            mImageView.setImageDrawable(getResources().getDrawable(R.drawable.icon_invisible));
            mTotalTextView.setText("*****");
        } else {
            mTotalTextView.setText(mTotal + "");
            mImageView.setImageDrawable(getResources().getDrawable(R.drawable.icon_visible));
        }

    }

    private void setAssetsATitle(String company) {
        //设置总资产文案
        mCollapsingToolbarLayout.setTitle(company);
    }

    /**
     * 数据处理 返回String 请求网络
     *
     * @param isLocal
     */
    @NonNull
    private void handlerData(boolean isLocal) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            if (null == mAssetsModelList || mAssetsModelList.size() == 0) {
                stringBuilder.append(Constants.ETH);
            } else {
                for (int i = 0; i < mAssetsModelList.size(); i++) {
                    stringBuilder.append(mAssetsModelList.get(i).id);
                    if (i != mAssetsModelList.size() - 1) {
                        stringBuilder.append(",");
                    }
                }
            }
            initData(stringBuilder, isLocal);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    Call<String> call;

    //网络获取数据
    private void initData(StringBuilder stringBuilder, boolean isLocal) {
        if (null == stringBuilder) {
            return;
        }
        APIModule
                .getApi()
                .querySymbol(mAddress, stringBuilder.toString())
                .enqueue(new APIListCallBack<AssetsModel>() {
                    @Override
                    protected void onResponse(List<AssetsModel> response) {
                        mResponse = response;
                        handler.sendEmptyMessage(0X98785);

                    }

                    @Override
                    protected void onResponseError(APIException e) {
                        setRefreshing(false);

                    }

                    @Override
                    protected void onFailureError(Call<String> call, Throwable t) {
                        setRefreshing(false);

                    }


                });
    }

    private void setRefreshing(final boolean refreshing) {
        mSwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(refreshing);
            }
        });
    }

    /**
     * 处理网络请求数据
     *
     * @param response
     */
    private void handleData(List<AssetsModel> response) {
        if (null != response && response.size() > 0) {
            if (null == mAssetsModelList) {
                mAssetsModelList = response;
            }

            for (AssetsModel assetsModel : mAssetsModelList) {
                for (AssetsModel model : response) {
                    if (assetsModel.id == model.id) {
                        assetsModel.balance = model.balance;
                        assetsModel.price = model.price;
                        assetsModel.address = UserInfo.get().address;
                    }
                }

            }
            calculatedValue();

            setAssetsATitleByAtate();
//            setTotalAndTitle();
            sortList();
            setNewData();
        }
    }


    //绑定适配器
    private void setAdapter() {
        //注册EventBus
        if (!isRegister()) {
            EventBus.getDefault().register(this);
        }
        mRecyclerView = $f(R.id.recyclerView);
        mAssetsAdapter = new AssetsAdapter(mAssetsModelList);
        mRecyclerView.setAdapter(mAssetsAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        //设置头部控件
        View view = View.inflate(mContext, R.layout.header_assets, null);
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        view.setLayoutParams(layoutParams);
        mAssetsAdapter.addHeaderView(view);
        mAssetsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

            }
        });
    }

    public boolean isRegister() {
        return EventBus.getDefault().isRegistered(this);
    }

    /**
     * 设置数据
     */
    private void setNewData() {
        mAssetsAdapter.setNewData(mAssetsModelList);
        mAssetsAdapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        isResume = true;
        super.onResume();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        try {
            if (isResume && !hidden) {
                handler.sendEmptyMessageDelayed(0X9520, 500);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onHiddenChanged(hidden);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0X9520:
                    onHiddenChanged();
                    break;

                case 0X98785:
                    handleData(mResponse);
                    setRefreshing(false);
                    break;
            }

            super.handleMessage(msg);
        }
    };

    private void onHiddenChanged() {


        if (null != mAssetsModelList && mAssetsModelList.size() > 0) {
            calculatedValue();
            setNewData();
            setAssetsATitleByAtate();
            handlerData(false);
        } else {
            initFirstData();
        }

    }

    /**
     * 排序保存
     */
    private void sortList() {
        if (null != mAssetsModelList && mAssetsModelList.size() > 0) {
            for (int i = 0; i < mAssetsModelList.size(); i++) {
                mAssetsModelList.get(i).postion = i;
                mAssetsModelList.get(i).isOpen = true;
                mAssetsModelList.get(i).point = 1;
                DaoManager.saveOrUpdate(mAssetsModelList.get(i));
            }

        }


    }

    @Override
    public void onDestroyView() {
        try {
            if (isRegister()) {
                EventBus.getDefault().unregister(this);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroyView();
    }


}
